package com.lw.interceptor;

import com.lw.common.IJsonResult;
import com.lw.utils.JsonUtils;
import com.lw.utils.MyStringUtil;
import com.lw.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 自定义拦截器
 */
public class MiniInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisOperator redisOperator;

    /**
     * 在controller调用前拦截
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String userId = httpServletRequest.getHeader("userId");
        String userToken = httpServletRequest.getHeader("userId");
        if(MyStringUtil.hasEmpty(userId,userToken)){//尚未登录
            returnErrorResponse(httpServletResponse,IJsonResult.errorTokenMsg("尚未登录"));
            return false;
        }else{
            //获取redis中的token 登录成功后会生成token放入redis中，并返回给用户
            String redisToken = redisOperator.get("user_redis_session:"+userId);
            /*
                一个账号只能在一台设备上登录，校验 userToken 是否和 redisToken相等。
                A手机用userId1账号登录，然后B手机用userId1账号登录，
                此时A手机请求时userId和userToken都有，但是和redis中保存的token不一致。
             */
            if(!userToken.equals(redisToken)){//已在其他设备登录
                returnErrorResponse(httpServletResponse,IJsonResult.errorTokenMsg("已在其他设备登录"));
                return false;
            }
        }
        return true;//true 请求正常，false 请求被拦截
    }

    public void returnErrorResponse(HttpServletResponse response, IJsonResult result){
        try(OutputStream out = response.getOutputStream()){
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        }catch (IOException e){

        }
    }

    /**
     * 在controller执行后，渲染视图前执行
     * 在以前的controller中还有转发、重定向行为，跳转到对应页面，即渲染视图
     * forward:/views/xxx.jsp
     * forward:/user/datail
     *
     * redirect:/views/xxx.jsp
     * redirect:/user/datail
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在controller执行后，渲染视图后执行
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
